import * as React from 'react';
import { Icon, Button, Steps, Modal } from 'antd';
import MyBread from '../../component/common/MyBread';
import { IStackViewPros } from '../../component/common/StackView';

import MForm from '../../component/form/MForm';
import LoadingComponent from '../../component/common/LoadingComponent';

import CustomerDetailStep1 from './detail-step/CustomerDetailsStep1';
import CustomerDetailStep2 from './detail-step/CustomerDetailsStep2';
import CustomerDetailStep3 from './detail-step/CustomerDetailsStep3';
import CustomerDetailStep4 from './detail-step/CustomerDetailsStep4';
import CustomerDetailStep5 from './detail-step/CustomerDetailsStep5';
import CustomerDetailStep6 from './detail-step/CustomerDetailsStep6';

import CustomerStore, { Customer } from './CustomerStore';

import CustomerInfo from './CustomerInfo';

const STEP_DATA = [
  { id: 0, name: '基本信息1' },
  { id: 1, name: '基本信息2' },
  { id: 2, name: '基本信息3' },
  { id: 3, name: '基本信息4' },
  { id: 4, name: '基本信息5' },
  { id: 5, name: '完成' },
];

interface IProps extends IStackViewPros {
  data?: any;
  callback?: any;
}
export default class CustomerDetail extends LoadingComponent<IProps, any>{ 
  public refs: {
    form1: any;
    form2: any;
    form3: any;
    form4: any;
    form5: any;
    form6: any;
  };
  private hasChanged = false;
  constructor(props: any) {
    super(props);
    this.state = Object.assign({
      btnLoading: false,
      addNewPage: true,
      current: 0,
      maxStep: 0,
      customer: {
        form0: {
          fields: {
            keys: []
          },
        },
        form1: {
          fields: {
          },
        },
        form2: {
          fields: {
          },
        },
        form3: {
          fields: {
          },
        },
        form4: {
          fields: {
          },
        },
      },
    }, this.state);
    this.hasChanged = false;
  }

  // shouldComponentUpdate?(nextProps: any, nextState: any, nextContext: any): boolean {
  //   let {current, maxStep} = nextState;
  //   return current <= maxStep;
  // }

  // 组件将要加载
  componentWillMount() {
    var state = {};
    if (this.props.data && this.props.data.id) {
      let customer: Customer = CustomerStore.get(this.props.data.id);
      if (customer) {
        state = {
          addNewPage: false,
          customer: customer
        };
      }
    }
    this.fetchLoad(state);
  }

  getFormKey = () => {
    let {current} = this.state;
    return `form${current}`;
  }

  onFieldsChange = (changedFields) => {
    this.hasChanged = true;
  }

  goBack = () => {
    if (this.hasChanged) {
      Modal.confirm({
        title: '提示',
        content: '数据尚未保存，确定离开页面吗？',
        onOk: () => {
          this.props.stackView.popView();
        }
      });
    } else {
      this.props.stackView.popView();
    }
  }

  goBackList = () => {
    let {callback} = this.props;
    let {addNewPage} = this.state;
    if (addNewPage && callback && callback.reload && typeof callback.reload === 'function') {
      callback.reload();
    }
    this.goBack();
  }

  viewInfo = () => {
    let {customer} = this.state;
    customer.current = 0;
    this.props.stackView.replaceView({
      name: '顾客信息',
      component: CustomerInfo,
      data: {
        id: customer.id
      }
    });
  }

  nextStep = () => {
    // this.setState({
    //   btnLoading: true
    // });
    // let form: MForm = this.refs[this.getFormKey()].refs.wrappedComponent.refs.formWrappedComponent as MForm;
    let form: MForm = super.getComponent(this.getFormKey());
    form.validateFields((errors, fields) => {
      if (!errors && fields) {
        this.saveFormFeilds(fields);
        let current = this.state.current;
        if (current === 4) {
          this.doSave();
        } else {
          this.toNextStep();
        }
      } else {
        // this.setState({
        //   btnLoading: false
        // });
      }
    });
  }

  prevStep = () => {
    const current = this.state.current - 1;
    this.setState({ current });
  }

  toNextStep = () => {
    let {current, maxStep, btnLoading} = this.state;
    current++;
    maxStep = Math.max(current, maxStep);
    btnLoading = false;
    this.setState({ current, maxStep, btnLoading });
  }

  doSave = () => {
    // 加入保存成功
    console.log('saving');
    let {customer} = this.state;
    if (!customer.id) {
      customer.id = new Date().getTime() + '';
    }

    // let item=Immutable.from(customer);
    let item = (customer);
    if (item.form2) {
      let {fields} = item.form2;
      if (fields['birthday']) {
        fields['birthday'] = fields['birthday'].format('YYYY-MM-DD');
      }
    }
    CustomerStore.save(item);
    this.toNextStep();
  }

  saveFormFeilds = (fields) => {
    let key = this.getFormKey();
    let {customer} = this.state;
    customer[key] = {
      'fields': fields
    };
    this.setState({
      customer
    });
  }



  renderStepBtn = () => {
    let {btnLoading, current} = this.state;
    const stepSize = STEP_DATA.length;
    if (current === 0) {
      return (
        <div className='break-no'>
          <Button type='ghost' onClick={this.goBack}><Icon type='rollback'></Icon>返&nbsp;&nbsp;&nbsp;回</Button>
          <Button type='primary' onClick={this.nextStep} loading={btnLoading}>下一步<Icon type='right'></Icon></Button>
        </div>
      );
    } else if (current > 0 && current < stepSize - 2) {
      return (
        <div className='break-no'>
          <Button type='ghost' onClick={this.prevStep}><Icon type='left'></Icon>上一步</Button>
          <Button type='primary' onClick={this.nextStep} loading={btnLoading}>下一步<Icon type='right'></Icon></Button>
        </div>
      );
    } else if (current === stepSize - 2) {
      return (
        <div className='break-no'>
          <Button type='ghost' onClick={this.prevStep}><Icon type='left'></Icon>上一步</Button>
          <Button type='primary' onClick={this.nextStep} loading={btnLoading}><Icon type='save'></Icon>保&nbsp;&nbsp;&nbsp;存</Button>
        </div>
      );
    }
  }

  renderStepContent = () => {
    let {customer, current, maxStep} = this.state;
    customer.form0.fields.id = customer.id;
    return (
      <div className='flex-grow-1 overflow-scroll relative'>
        {
          maxStep >= 0 && maxStep <= 4 ? <CustomerDetailStep1 ref='form0' show={current === 0}  {...customer.form0.fields} onSubmit={this.nextStep} onChange={this.onFieldsChange} /> : null
        }
        {
          maxStep >= 1 && maxStep <= 4 ? <CustomerDetailStep2 ref='form1' show={current === 1} {...customer.form1.fields} onSubmit={this.nextStep} onChange={this.onFieldsChange} /> : null
        }
        {
          maxStep >= 2 && maxStep <= 4 ? <CustomerDetailStep3 ref='form2' show={current === 2} {...customer.form2.fields} onSubmit={this.nextStep} onChange={this.onFieldsChange} /> : null
        }
        {
          maxStep >= 3 && maxStep <= 4 ? <CustomerDetailStep4 ref='form3' show={current === 3} {...customer.form3.fields} onSubmit={this.nextStep} onChange={this.onFieldsChange} /> : null
        }
        {
          maxStep >= 4 && maxStep <= 4 ? <CustomerDetailStep5 ref='form4' show={current === 4} {...customer.form4.fields} onSubmit={this.nextStep} onChange={this.onFieldsChange} /> : null
        }
        {
          maxStep >= 5 ? <CustomerDetailStep6 ref='form5' show={current === 5} showLoading={false} onSubmit={this.viewInfo} onClose={this.goBackList} /> : null
        }
      </div>
    );
  }


  renderUI() {
    const { current } = this.state;
    return (
      <div className='view-inner flex-row'>
        <div className='view__banner flex-col'>
          <div className='flex-grow-1'>
            <MyBread stackView={this.props.stackView} />
          </div>
          <div className='break-no'>
            {this.renderStepBtn()}
          </div>
        </div>
        <div className='view__content flex-row flex-grow-1 overflow-hidden'>
          <div className='view-step-bar'>
            <Steps current={current}>
              {STEP_DATA.map(item => <Steps.Step key={item.name} title={item.name} />)}
            </Steps>
          </div>
          {this.renderStepContent()}
        </div>
      </div>
    );
  }
}

